﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace UpdateProcess
{
    public partial class UpdateProcess : Form
    {
        public UpdateProcess()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void UpdateProcess_Load(object sender, EventArgs e)
        {
            this.ShowInTaskbar = false;
            lblTitle.Text = "程序正在检查新版本...";
            ThreadStart threadStart = new ThreadStart(Download);
            Thread thread = new Thread(threadStart);
            thread.Start();
        }

        public void Download()
        {
            try
            {
                string xmlPath = Application.StartupPath + "\\AutoUpdater.xml";
                string tempPath = Application.StartupPath + "\\TempUpdate\\";
                DataSet ds = XmlProvider.GetXml(xmlPath);
                //获取当前更新服务器网址和当前版本号
                string updateURL = Trim(ds.Tables["URLAddres"].Rows[0][0]);
                string version = Trim(ds.Tables["Version"].Rows[0][0]);
                string OldAppName = Trim(ds.Tables["AppName"].Rows[0][0]);
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }

                WebClient wc = new WebClient();
                wc.DownloadFile(updateURL + "AutoUpdater.xml", tempPath + "AutoUpdater.xml");
                DataSet dsDown = XmlProvider.GetXml(tempPath + "AutoUpdater.xml");
                //服务器上的版本号
                string downVersion = Trim(dsDown.Tables["Version"].Rows[0][0]);
                if (downVersion != version)
                {
                    this.WindowState = FormWindowState.Normal;
                    this.TopMost = true;
                    lblTitle.Text = "程序正在更新，请稍后...";
                    Process[] ps = Process.GetProcesses();
                    foreach (Process item in ps)
                    {
                        if (OldAppName.IndexOf(item.ProcessName)>=0)
                        {
                            item.Kill();
                        }
                    }
                    String[] UpdateFiles = new String[dsDown.Tables["UpdateFile"].Rows.Count];
                    for (int i = 0; i < dsDown.Tables["UpdateFile"].Rows.Count; i++)
                    {
                        UpdateFiles[i] = Trim(dsDown.Tables["UpdateFile"].Rows[i][0]);
                    }
                    string reStart = Trim(dsDown.Tables["ReStart"].Rows[0][0]);
                    string startAppName = Trim(dsDown.Tables["AppName"].Rows[0][0]);
                    for (int i = 0; i < UpdateFiles.Length; i++)
                    {
                        lblTitle.Text = "正在下载" + UpdateFiles[i] + "....";
                        wc.DownloadFile(updateURL + UpdateFiles[i], tempPath + UpdateFiles[i]);
                        progressBar1.Value =Convert.ToInt32((i + 1) / UpdateFiles.Length * 100);
                        //测试用
                        Thread.Sleep(500);
                    }
                    if (OldAppName != startAppName)
                    {
                        try
                        {
                            File.Move(Application.StartupPath + "\\" + OldAppName, Application.StartupPath + "\\" + startAppName);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    for (int i = 0; i < UpdateFiles.Length; i++)
                    {
                        try
                        {
                            File.Replace(tempPath + UpdateFiles[i], Application.StartupPath + "\\" + UpdateFiles[i], Application.StartupPath + "\\" + UpdateFiles[i] + "_bak");
                            File.Delete(Application.StartupPath + "\\" + UpdateFiles[i] + "_bak");
                        }
                        catch (Exception)
                        {
                            try
                            {
                                File.Move(tempPath + UpdateFiles[i], Application.StartupPath + "\\" + UpdateFiles[i]);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    if (reStart.ToLower() == "yes")
                    {
                        this.Hide();
                        Process.Start(Application.StartupPath + "\\" + startAppName);
                    }

                }
                Application.Exit();
            }
            catch (Exception)
            {
                Application.Exit();
            }
            //Thread.CurrentThread.Abort();
        }
        /// <summary>
        /// 去空格
        /// </summary>
        /// <param name="temp"></param>
        /// <returns></returns>
        public string Trim(Object temp)
        {
            try
            {
                string t = temp.ToString().Trim();
                return t;
            }
            catch (Exception e)
            {
                return "";
            }
        }
    }
}
